﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.Web.Infrastructure;
using KBVault.DAL.Repository;
using KBVault.DAL.Entities;


namespace KBVault.Web.Application.UC.Articles
{
    public partial class ListArticles : KBVaultBaseUserControl
    {
        

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                if ((this.Page as KBVaultAdminPage).ActiveCategoryId > 0)
                {

                    try
                    {
                        Category c = CategoryRepository.Get((this.Page as KBVaultAdminPage).ActiveCategoryId);
                        editCategoryLink.NavigateUrl = "~/Application/CategoryOps.aspx?Op=edit&Category=" + c.Id;
                        lbCategoryTitle.Text = c.Name;
                        rptArticles.DataSource = c.Articles;
                        rptArticles.DataBind();
                        btnDeleteCategory.Visible = c.Articles.Count == 0;                        
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                        ShowExceptionMessage();
                    }
                }
            }
        }

        protected void rptArticles_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteArticle")
            {
                try
                {
                    ArticleRepository.Delete(Convert.ToInt32(e.CommandArgument));
                    Category c = CategoryRepository.Get((this.Page as KBVaultAdminPage).ActiveCategoryId);
                    rptArticles.DataSource = c.Articles;
                    rptArticles.DataBind();
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message);
                    ShowExceptionMessage();
                }
            }
        }

        protected void btnDeleteCategory_Click(object sender, EventArgs e)
        {
            try
            {
                CategoryRepository.Delete(((this.Page as KBVaultAdminPage).ActiveCategoryId));
                Response.Redirect("/Application/CategoryOps.aspx?Op=list");
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                ShowExceptionMessage();
            }

        }
        
        
    }
}